package org.king.handler;

import jakarta.annotation.Resource;
import jakarta.validation.ValidationException;
import org.king.exception.BaseException;
import org.king.pojo.RestBean;
import org.king.util.logUtil.ConsoleLogUtil;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.king.constant.MessageConst;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
public class GlobalExceptionHandler {
    @Resource
    private ConsoleLogUtil logUtil;

    @ExceptionHandler(ValidationException.class)
    public RestBean<Void> handleValidationException(ValidationException e) {
        logUtil.error(e, e.getMessage());
        return RestBean.failure(400, "请求参数有误");
    }

    @ExceptionHandler(BaseException.class)
    public RestBean<Void> handleBaseException(BaseException e) {
        logUtil.warn(e, e.getMessage());
        return RestBean.failure(400, e.getMessage());
    }

    @ExceptionHandler
    public RestBean<Void> SQLExceptionHandler(SQLIntegrityConstraintViolationException e){
        String msg=e.getMessage();
        String[] split = msg.split(" ");//按空格分割出来字符串数组
        if (msg.contains("Duplicate entry")){//数据库中存在重复条目
            String name = split[2];
            logUtil.error(e, name + MessageConst.ALREADY_EXISTS);
        }else{
            logUtil.error(e, MessageConst.UNKNOWN_ERROR);
        }
        return RestBean.failure(400 , MessageConst.SERVICE_INNER_ERROR);
    }
}
